package store

import (
    "math/big"
    "github.com/tecbot/gorocksdb"
)

type CounterOperator struct {
    counter int64
}

func NewCounterOperator() gorocksdb.MergeOperator {
    return &CounterOperator{0}
}

func (c *CounterOperator) FullMerge(key, existingValue []byte, operands [][]byte) ([]byte, bool) {
    counter := big.NewInt(0)
    if existingValue == nil {
        return nil, false
    }
    if err := counter.UnmarshalText(existingValue); err != nil {
        return nil, false
    }
    counter.Add(counter, big.NewInt(c.counter))
    r, err := counter.MarshalText()
    if err != nil {
        return nil, false
    }
    c.counter = 0
    return r, true
}

func (c *CounterOperator) PartialMerge(key, leftOperand, rightOperand []byte) ([]byte, bool) {
    c.counter += 2
    return nil, true
}

// The name of the MergeOperator.
func (u *CounterOperator) Name() string {
    return "Unique"
}
